package com.haople.sso.web.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.haople.sso.core.authentication.UserAuthorization;

@Controller
public class ChangePasswordController {

	private static final Logger logger=Logger.getLogger(ChangePasswordController.class);
	private static final String CHANGE_PASSWORD_ERROR_MSG="change_password_error_msg";
	private static final String ERROR_MSG="error_msg";
	
	@Autowired
	private UserAuthorization  userAuthorization;
	
	@RequestMapping(value = "/toChangePassword")
	public String toRegister() {
		return "change-password";
	}
	
	/**
	 * 注册用户信息
	 * @param userName
	 * @param password
	 * @param captcha
	 * @param redirectAttributes
	 * @param httpSession
	 * @return
	 */
	@RequestMapping(value = "/changePassword", method = RequestMethod.POST)
	public String register(String userName, String oldPassword,String newPassword , RedirectAttributes redirectAttributes,
			HttpSession httpSession) {
		try {
			if(StringUtils.isEmpty(userName)){
				redirectAttributes.addFlashAttribute(CHANGE_PASSWORD_ERROR_MSG, "用户名为空！");
				return "redirect:/toChangePassword";
			}
			if(StringUtils.isEmpty(oldPassword)){
				redirectAttributes.addFlashAttribute(CHANGE_PASSWORD_ERROR_MSG, "原密码为空！");
				return "redirect:/toChangePassword";
			}
			if(StringUtils.isEmpty(newPassword)){
				redirectAttributes.addFlashAttribute(CHANGE_PASSWORD_ERROR_MSG, "新密码不可为空！");
				return "redirect:/toChangePassword";
			}
			if(userAuthorization.authorization(userName, oldPassword)==null){ //如果用户原密码验证不成功
				redirectAttributes.addFlashAttribute(CHANGE_PASSWORD_ERROR_MSG, "原密码不正确");
				return "redirect:/toChangePassword";
			}
			if(!userAuthorization.changePassword(userName, newPassword)) {
				redirectAttributes.addFlashAttribute(CHANGE_PASSWORD_ERROR_MSG, "密码修改失败");
				return "redirect:/toChangePassword";
			}
			return "redirect:/changePassword-success";
		} catch (Exception e) {
			logger.error("------------用户注册异常--------------", e);
			redirectAttributes.addFlashAttribute(ERROR_MSG, "系统错误");
			return "redirect:/error";
		}
	}
	
	@RequestMapping("/changePassword-success")
	public String register(Model model,String k,HttpServletRequest request,RedirectAttributes redirectAttributes){
		   return "register-success";
	}
}
